package api

import (
	"encoding/json"
	"net/http"
	"stacks/database"
)

func healthHandler(w http.ResponseWriter, r *http.Request) {
	// 获取数据库连接
	db := database.GetRawDB()
	if db == nil {
		w.WriteHeader(http.StatusServiceUnavailable)
		json.NewEncoder(w).Encode(map[string]string{
			"status": "unhealthy",
			"error":  "Database not initialized",
		})
		return
	}

	// 检查数据库连接
	sqlDB, err := db.DB()
	if err != nil {
		w.WriteHeader(http.StatusServiceUnavailable)
		json.NewEncoder(w).Encode(map[string]string{
			"status": "unhealthy",
			"error":  "Database connection failed",
		})
		return
	}

	if err := sqlDB.Ping(); err != nil {
		w.WriteHeader(http.StatusServiceUnavailable)
		json.NewEncoder(w).Encode(map[string]string{
			"status": "unhealthy",
			"error":  "Database ping failed",
		})
		return
	}

	// 获取Redis连接
	rdb := database.GetRedis()
	if rdb == nil {
		w.WriteHeader(http.StatusServiceUnavailable)
		json.NewEncoder(w).Encode(map[string]string{
			"status": "unhealthy",
			"error":  "Redis not initialized",
		})
		return
	}

	// 检查Redis连接
	if _, err := rdb.Ping(r.Context()).Result(); err != nil {
		w.WriteHeader(http.StatusServiceUnavailable)
		json.NewEncoder(w).Encode(map[string]string{
			"status": "unhealthy",
			"error":  "Redis connection failed",
		})
		return
	}

	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(map[string]string{
		"status": "healthy",
	})
}
